package com.wgz.flag.controller;

import com.wgz.flag.common.Result;
import com.wgz.flag.domain.dto.LoginDto;
import com.wgz.flag.domain.dto.RegisterDto;
import com.wgz.flag.domain.dto.ResetPasswordDto;
import com.wgz.flag.domain.vo.UserLoginVo;
import com.wgz.flag.entity.User;
import com.wgz.flag.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@CrossOrigin(origins = { "http://localhost:8081", "http://localhost:8082" }, allowCredentials = "true")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/getAll")
    public Result<List<User>> getUsers(User user) {
        List<User> users = userService.getAllUsers(user);
        return Result.success(users);
    }

    @GetMapping("/getById/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = userService.selectById(id);
        return Result.success(user);
    }

    @GetMapping("/getInfo")
    public Result<List<User>> getUserInfo() {
        List<User> users = userService.getAllUserInfo();
        return Result.success(users);
    }

    @PostMapping("/update")
    public Result<String> updateUserInfo(@RequestBody User user) {
        userService.updateUserInfo(user);
        return Result.success("更新成功！");
    }

    @PostMapping("/login")
    public Result<UserLoginVo> login(@RequestBody(required = true) LoginDto loginDto) {
        UserLoginVo userLoginVo = userService.login(loginDto);
        return Result.success(userLoginVo);
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterDto registerDto) {
        userService.register(registerDto);
        return Result.success("注册成功！");
    }

    /**
     * 修改密码
     */
    @PostMapping("/resetPassword")
    public Result<String> updateUserPassword(@RequestBody ResetPasswordDto resetPasswordDto) {
        userService.updateUserPassword(resetPasswordDto);
        return Result.success("密码修改成功");
    }

    /**
     * 更新用户头像
     * @param file 上传的图片文件
     * @return 图片访问地址
     */
    @PostMapping("/uploadAvatar")
    public Result<String> uploadAvatar(@RequestParam("avatar") MultipartFile file) {
        String avatarUrl = userService.uploadAvatar(file);
        return Result.success(avatarUrl);
    }
}